/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.common.application.user;

import com.alibaba.fastjson2.JSONObject;
import com.qishuihe.basedomain.infrastructure.aspect.LogAnnotation;
import com.qishuihe.basedomain.infrastructure.vo.LoginUserVO;
import com.qishuihe.baseinterface.constant.CommonConstant;
import com.qishuihe.baseinterface.utils.JWTUtil;
import com.qishuihe.baseinterface.utils.ListUtil;
import com.qishuihe.common.domain.role.service.RoleUserRelationService;
import com.qishuihe.common.domain.user.entity.UserEntity;
import com.qishuihe.common.domain.user.service.UserService;
import com.qishuihe.common.infrastructure.common.RestPassWordProperties;
import com.qishuihe.common.infrastructure.mail.MailSendHandler;
import com.qishuihe.common.infrastructure.mail.vo.MyMailVO;
import com.qishuihe.common.infrastructure.utils.VerifyCodeUtils;
import com.qishuihe.baseinterface.basevo.vo.ResultVO;
import com.qishuihe.baseinterface.basevo.vo.ResultPageVO;
import com.qishuihe.outbound.user.IUser;
import com.qishuihe.outbound.user.QueryPageDTO;
import com.qishuihe.outbound.user.RegisteredUserDTO;
import com.qishuihe.outbound.user.RoleUserDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping()
public class UserControl implements IUser {

    @Autowired
    private UserService userServiceImpl;



    @Autowired
    private RoleUserRelationService roleUserRelationServiceImpl;



    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestPassWordProperties restPassWordProperties;

    @Autowired
    private MailSendHandler mailSendHandler;

    @Override
    @LogAnnotation
    public ResultVO<RegisteredUserDTO> modfiyUser(@RequestBody RegisteredUserDTO registeredUserDTO) {
        ResultVO<RegisteredUserDTO> registeredUserVOResultDto = new ResultVO<RegisteredUserDTO>();
        if(null==registeredUserDTO.getId()){
            registeredUserVOResultDto.setMessage("修改用户时Id不能为空");
            return registeredUserVOResultDto;
        }
        registeredUserVOResultDto = userServiceImpl.modifyUser(registeredUserDTO);
        return registeredUserVOResultDto;
    }

    @Override
    @LogAnnotation
    public ResultPageVO<RegisteredUserDTO> queryUser(@RequestBody QueryPageDTO<RegisteredUserDTO> queryPageDTO) {
        ResultPageVO<RegisteredUserDTO> registeredUserVOResultPageVO = userServiceImpl.queryUser(queryPageDTO);
        return registeredUserVOResultPageVO;
    }

    @Override
    @LogAnnotation
    public ResultVO deletUserByIds(Long[] ids) {
        ResultVO resultVO = new ResultVO();
         if(!userServiceImpl.removeByIds(Arrays.asList(ids))){
             resultVO.setCode(CommonConstant.STATUS_ERROR);
             resultVO.setMessage("删除失败");
         }
        return resultVO;
    }

    @Override
    @LogAnnotation
    public ResultVO deletUserById(@PathVariable(name="id") Long id) {
        ResultVO resultVO = new ResultVO();
        if(!userServiceImpl.removeById(id)){
            resultVO.setCode(CommonConstant.STATUS_ERROR);
            resultVO.setMessage("删除失败");
        }
        return resultVO;
    }

    @Override
    public ResultVO<RegisteredUserDTO> queryUserById(@PathVariable(name="id") Long id) {
        RegisteredUserDTO registeredUserDTO = new RegisteredUserDTO();
       UserEntity userEntity = userServiceImpl.getById(id);
        BeanUtils.copyProperties(userEntity,registeredUserDTO);
        ResultVO<RegisteredUserDTO> registeredUserVOResultDto = new ResultVO<RegisteredUserDTO>();
        registeredUserVOResultDto.setObj(registeredUserDTO);
        return registeredUserVOResultDto;
    }

    @Override
    @LogAnnotation
    public ResultVO<RoleUserDTO> modfiyRoleUser(@RequestBody RoleUserDTO roleUserDTO) {
        return roleUserRelationServiceImpl.modifyRoleUser(roleUserDTO);
    }


    @Override
    @LogAnnotation
    public ResultVO<String> resetwd(String wd) {
        ResultVO<String> resultVO = new ResultVO<String>();
        //获取oken
        //根据email获取用户
        //用email生成token
        //用token发送链接
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUserVO loginUserDTO = (LoginUserVO)usernamePasswordAuthenticationToken.getPrincipal();
        RegisteredUserDTO registeredUserDTO = new RegisteredUserDTO();
        registeredUserDTO.setId(loginUserDTO.getId());
        registeredUserDTO.setPassword(wd);
        ResultVO<RegisteredUserDTO> registeredUserVOResultDto = userServiceImpl.modifyUser(registeredUserDTO);
        resultVO.setCode(registeredUserVOResultDto.getCode());
        resultVO.setMessage(registeredUserVOResultDto.getMessage());
        stringRedisTemplate.delete(loginUserDTO.getUsername());
        return resultVO;
    }

    @Override
    @LogAnnotation
    public ResultVO<String> sendResetLink(String email) {
        ResultVO<String> resultVO = new ResultVO<String>();
        //验证email有效
        //用email生成token
        //用token发送链接
        QueryPageDTO<RegisteredUserDTO> queryPageDTO = new QueryPageDTO<>();
        RegisteredUserDTO registeredUserDTO = new RegisteredUserDTO();
        registeredUserDTO.setEmail(email);
        queryPageDTO.setParamObj(registeredUserDTO);
        ResultPageVO<RegisteredUserDTO> registeredUserDTOResultPageVO =  userServiceImpl.queryUser(queryPageDTO);
        if(ListUtil.isEmpty(registeredUserDTOResultPageVO.getRecords())){
            resultVO.setMessage("邮箱不存在");
            resultVO.setCode(CommonConstant.STATUS_ERROR);
            return resultVO;
        }
        BeanUtils.copyProperties(registeredUserDTOResultPageVO.getRecords().get(0),registeredUserDTO);

        String token = JWTUtil.createJWT(registeredUserDTO.getUsername());
        stringRedisTemplate.opsForValue().set(registeredUserDTO.getUsername(), JSONObject.toJSONString(registeredUserDTO), restPassWordProperties.getValidTime(), TimeUnit.MINUTES);
        MyMailVO myMailVO  = new MyMailVO();
        myMailVO.setTo(email);
        myMailVO.setSubject(restPassWordProperties.getSubject());
        String frontPage= restPassWordProperties.getFrontPage()+"/"+token;
        String text = restPassWordProperties.getHtml().replace(CommonConstant.REST_USER_NAME,registeredUserDTO.getUsername())
                .replace(CommonConstant.FRONT_PAGE_SIT,frontPage).replace(CommonConstant.VALID_TIME,String.valueOf(restPassWordProperties.getValidTime()));
        myMailVO.setText(text);
        mailSendHandler.senMimeMail(myMailVO,false);
        return resultVO;
    }

    @LogAnnotation
    public ResultVO<String> sendVerifyCode(String email) {
        ResultVO<String> resultVO = new ResultVO<String>();

        String code="";
        //此处的代码有点问题，大家考虑下咋么实现
        while(true){
             code= VerifyCodeUtils.generateVerifyCode();
             if(stringRedisTemplate.opsForValue().setIfAbsent( code,code,restPassWordProperties.getValidTime(), TimeUnit.MINUTES)){
                 break;
             }
        }
        MyMailVO myMailVO  = new MyMailVO();
        myMailVO.setTo(email);
        myMailVO.setSubject(restPassWordProperties.getSubject());

        String text = restPassWordProperties.getText().replace(CommonConstant.VERIFY_CODE,code)
                      .replace(CommonConstant.VALID_TIME,String.valueOf(restPassWordProperties.getValidTime()));
        myMailVO.setText(text);
        mailSendHandler.senSimpleMail(myMailVO);
        return resultVO;
    }
}
